<?php
/**
 * Created by PhpStorm.
 * User: xiangfeng
 * Date: 2022/4/9
 * Time: 2:09 AM
 */

namespace app\api\http\middleware;

use app\api\extend\tools\JwtAuth;
use app\api\http\exceptions\ApiErr;
use app\api\http\exceptions\ApiExceptions;
use think\Request;

/**
 *登录中间件
 * Class JwtAuthMiddleware
 * @package app\api\http\middleware
 */
class JwtAuthMiddleware extends BaseMiddleware
{
    /**
     * @param Request $request
     * @param \Closure $next
     * @return mixed
     * @throws ApiExceptions
     */
    public function handle(Request $request, \Closure $next)
    {
        $redis = $this->redis;
        $header = $request->header();
        $token = isset($header['token']) ? $header['token'] : '';

        $jwtAuth = JwtAuth::getInstance();
        if ($token && $token != "null") {
            try {
                $jwtAuth->setToken($token);
                if ($jwtAuth->validateToken() && $jwtAuth->verifyToken()) {
                    $uid = $jwtAuth->decode_jwt_token()->getClaim('uid');
                    $rid = $jwtAuth->decode_jwt_token()->getClaim('rid');
                    $redis_token = $redis->hGetAll(USER_TOKEN_PREFIX . md5($token)); //获取缓存用户数据
                    $cache_token = isset($redis_token['token']) ? $redis_token['token'] : '';
                    $user_id = isset($redis_token['user_id']) ? $redis_token['user_id'] : 0;
                    $role_id = isset($redis_token['role_id']) ? $redis_token['role_id'] : 0;
                    if ($token != $cache_token) {
                        throw new ApiExceptions(ApiErr::ERROR_TOKEN);
                    }
                    if ($user_id != $uid || $role_id != $rid) {
                        throw new ApiExceptions(ApiErr::ILLEGAL_USER_WARRING);
                    }
                    //检测用户账号状态.....（token 有效期2个小时，暂时不做校验）
                    return $next($request);
                }
            } catch (\Exception $exception) {
                throw new ApiExceptions(ApiErr::INVALID_TOKEN);
            }

        } else {
            throw new ApiExceptions(ApiErr::ERROR_TOKEN);
        }
    }
}